

package dao

import (
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/frame/gmvc"
	"guli-shopping/product-service/protobuff/productProto"
)

var (
	 //直接填充,this里也能用
	 PmsCategoryDao = &pmscategoryDao{
		 M:g.DB().Table("pms_category").Safe(),
	 }
)

type pmscategoryDao struct {
	gmvc.M
}

func (this *pmscategoryDao) FindTree() ([]*productProto.PmsCategory,error) {

	//查询所有
	dao := this.Clone()
	all,_:=dao.Fields("cat_id","name","parent_cid").All()
	var newArray []*productProto.PmsCategory
	err := all.Structs(&newArray)
	if err!=nil {
		return nil,errors.New("查询失败")
	}

	categories := []*productProto.PmsCategory{}
	for _, value := range newArray {
		//所有ParentCid=0的,也就是根级别的,往它的children里设置东西
		if value.ParentCid==0 {
			for _, child := range newArray {
				if value.CatId==child.ParentCid {
					value.Children=append(value.Children,child)
					for _, two := range newArray {
						if child.CatId==two.ParentCid {
							child.Children=append(child.Children,two)
						}
					}
				}
			}
			categories=append(categories,value)
		} else {
			//可以直接break,因为查询出来的是数组,一但parentID!=0了,后面的都不会是0
			break
		}
	}

	return categories,nil
}

func (this *pmscategoryDao) FindAll(query *productProto.PmsCategoryQuery) ([]*productProto.PmsCategory,int,error) {
    //分页,如果要添加条件,在这里添加
    count, _ := this.OmitEmpty().Count()
	all, err := this.OmitEmpty().Page(int(query.Page), int(query.Size)).All()
	models := []*productProto.PmsCategory{}
	err = all.Structs(&models)
	if err != nil {
		return nil,0,errors.New("查询失败")
	}
	return models,count,err
}

func (this *pmscategoryDao) FindById(id int64) (*productProto.PmsCategory,error) {
	all, err := this.WherePri(id).FindOne()
	if err != nil {
		return nil,errors.New("查询失败")
	}
	models := &productProto.PmsCategory{}
	all.Struct(models)
	return models,err
}

func (this *pmscategoryDao) Delete(ids[]int64) error {

	all, _ := this.WherePri(ids).Count()
	//要删除的数量不匹配
	if  len(ids)!=all{
		return errors.New("删除失败")
	}
	_, err := this.WherePri(ids).Delete()
	return err
}

func (this *pmscategoryDao) Update(req *productProto.PmsCategory) error {
	_, err := this.OmitEmpty().WherePri(req.CatId).Data(req).Update()
	return err
}
func (this *pmscategoryDao) Save(req *productProto.PmsCategory) (int64,error) {
	all, err := this.Data(req).Save()
	if err!=nil {
		return 0,errors.New("保存失败")
	}
	id, _ := all.LastInsertId()
	return id,nil
}




